<template>
  <div>
    <CategorySelector :isForbiddenForm="isShowAttrList"></CategorySelector>
    <el-card>
      <div v-if="isShowAttrList">
        <el-button :disabled="!categoryStore.category3Id" type="primary" :icon="Plus" @click="toSaveAttrValue">添加属性
        </el-button>
        <el-table v-loading="loading" :data="attrList" border style="margin-top:10px">
          <el-table-column label="序号" width="80px" type="index" algin="center"></el-table-column>
          <el-table-column label="属性名称" prop="attrName">
          </el-table-column>
          <el-table-column label="属性值列表">
            <template v-slot="{ row }">
              <el-tag v-for="attrValue in row.attrValueList" :key="attrValue.id" style="margin-right:8px">
                {{ attrValue.valueName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row, $index }">
              <el-button title="修改" size="small" type="warning" :icon="Edit" @click="toEditAttr(row)" />
              <el-popconfirm confirm-button-text="确认" cancel-button-text="取消" :icon="InfoFilled" icon-color="#626AEF"
                title="确定要删除此条属性吗?" @confirm="confirmDeleteAttr(row.id)" @cancel="cancelEvent">
                <template #reference>
                  <el-button title="删除" size="small" type="danger" :icon="Delete" />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else>
        <el-form>
          <el-form-item label="属性名" style="width:300px">
            <el-input placeholder="请输入属性名" wdith="200px" v-model="attrInfo.attrName"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :disabled="!attrInfo.attrName" :icon="Plus" @click="addValue">添加属性值
            </el-button>
            <el-button type="default" @click="isShowAttrList = true">取消</el-button>
          </el-form-item>
        </el-form>
        <el-table border :data="attrInfo.attrValueList" style="margin-bottom:10px;">
          <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
          <el-table-column label="属性值名称">
            <template v-slot="{ row, $index }">
              <el-input ref="inputRef" v-if="row.isShowInput" v-model="row.valueName" size="small"
                @blur="deleteCurrentRow(row, $index)"></el-input>
              <span v-else @dblclick="toEditAttrValue(row, $index)" style="display:inline-block;width:100%">{{
                  row.valueName
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row, $index }">
              <el-popconfirm confirm-button-text="确认" cancel-button-text="取消" :icon="InfoFilled" icon-color="#626AEF"
                title="确定要删除此条属性值吗?" @confirm="confirmEventAttrValue($index)">
                <template #reference>
                  <el-button title="删除" size="small" type="danger" :icon="Delete" />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="saveAttrInfo" :disabled="!attrInfo.attrValueList.length">保存</el-button>
        <el-button type="default" @click="isShowAttrList = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import CategorySelector from '@/components/CategorySelector/index.vue'
export default {
  name: 'Attr',
  components: { CategorySelector }
}
</script>

<script lang="ts" setup>
import { reactive, ref, watch, nextTick } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { InfoFilled } from '@element-plus/icons-vue'
import { useCategoryListStore } from '@/stores/categoryList'
import { reqAddOrUpdateAttrInfo, reqDeleteOneAttr, reqGetAttrListData } from '@/api/product/attr'
import { ElMessage } from 'element-plus'
import type { AttrInfoModel, AttrListModel, AttrValueInfoModel } from '@/api/product/model/attrModel'

const isShowAttrList = ref<boolean>(true)

// 定义一个数组来存储属性列表数据
const attrList = ref<AttrListModel>([])

// const inputRef = ref<HTMLInputElement>()

// 定义一个变量 为对应输入框 以便用于获取输入框对象
const inputRef = ref(null)

// 定义一个属性对象，用于收集要添加的属性信息
const attrInfo = reactive({
  attrName: '', // 要存储的属性名
  attrValueList: [], // 存储属性的数组
  categoryLevel: 3, // 等级
  categoryId: -1 // id值
})

// 页面中的loading效果
const loading = ref<boolean>(false)

// 获取store
const categoryStore = useCategoryListStore()

// 1. 定义一个根据一二三级导航获取属性列表的函数
const getAttrListData = async () => {
  // 请求之前开启loading效果
  loading.value = true
  const result = await reqGetAttrListData({
    category1Id: categoryStore.category1Id as number,
    category2Id: categoryStore.category2Id as number,
    category3Id: categoryStore.category3Id as number
  })

  attrList.value = result
  // 清除loading效果
  loading.value = false
}

// 2. 监听三级导航ID的变化 进而发送请求获取列表数据
watch(() => categoryStore.category3Id, async (category3Id) => {
  // console.log('监听执行了...',newValue,oldValue)
  if (!category3Id) {
    // 数组列表要清空
    attrList.value = []  // 将数据内容清空，不要显示属性列表了
    return //如果category3Id为空 不要再发送请求了
  }

  // 调用方法，获取属性列表 
  getAttrListData()
}, { immediate: true })  // 注意此时要开启立即监视

// 3.删除数据
const confirmDeleteAttr = async (id: number) => {
  await reqDeleteOneAttr(id)

  // 成功之后要重新发送请求
  getAttrListData()
}

// 4. 添加属性  其实就是给attrInfo.attrValueList数组中添加内容
const addValue = () => {
  attrInfo.attrValueList.push({
    valueName: '',
    attrId: attrInfo.id, // 编辑的时候使用
    isShowInput: true // 是不是显示输入框  还是说显示一个span标签
  })

  nextTick(() => {
    inputRef.value?.focus()
  })
}


// 5. 输入框失去焦点时，删除当前行，也就是删除数组中的那一项数据
const deleteCurrentRow = (row: AttrValueInfoModel, index: number) => {
  if (!row.valueName) {
    attrInfo.attrValueList.splice(index, 1)
    return
  }
  row.isShowInput = false
}

// 6. 删除属性
const confirmEventAttrValue = (index: number) => {
  attrInfo.attrValueList.splice(index, 1)
}


// 7. 修改属性值
const toEditAttrValue = (row: AttrValueInfoModel) => {
  row.isShowInput = true

  nextTick(() => {
    inputRef.value?.focus()
  })
}

// 8. 添加新属性时，清空原值
const toSaveAttrValue = () => {
  // 要显示添加属性的页面
  isShowAttrList.value = false

  // 清空旧值
  attrInfo.attrName = ''
  attrInfo.attrValueList = []
  delete attrInfo.id
}

// 9. 实现属性对象的添加功能
const saveAttrInfo = async () => {
  attrInfo.categoryId = categoryStore.category3Id
  // attrInfo.attrValueList.forEach(attrValue=>{
  //   delete attrValue.isShowInput
  // })
  await reqAddOrUpdateAttrInfo(attrInfo)
  ElMessage.success('属性添加成功')

  // 跳转到列表页
  isShowAttrList.value = true

  // 重新获取一下页面中的数据
  getAttrListData()
}

//10. 更新属性之数据回显
const toEditAttr = (row: AttrInfoModel) => {
  isShowAttrList.value = false

  // attrInfo = row // 不能这样直接赋值
  Object.assign(attrInfo, row)
}
</script>


<style>
</style>
